using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoreData;
using EntityData;
using Helper;
using System.Threading;
using System.Web.Mvc;
using Services.OpenIDHost;
namespace Services
{

    public partial class usersService
    {
       readonly IusersEntity entity;
     //  SocketClient socket;
     // readonly OpenIDHost.OpenIDServiceClient OpenID;
       public usersService()
       {
           this.entity = new usersEntity();
          //// socket = new SocketClient();
          // try
          // {
          //     if(OpenID==null||(OpenID.State==System.ServiceModel.CommunicationState.Closed))
          //     {
          //     OpenID = new OpenIDServiceClient();
          //     OpenID.Open();
          //     }
          // }
          // catch { }

       }

       string state;
        void StartSocket()
       {
           //if(SessionManagement.GetSessionReturnToString("UserName")!=null)
           //    socket.Start(SessionManagement.GetSessionReturnToString("UserName"), out state);
           //else
           //    socket.Start("Anonymous", out state);
        }

       #region Main Method



       /// <summary>
       /// Save 
       /// </summary>
       /// <param name="_model"></param>
       /// <returns></returns>
       public long Save(object _model, out string error)//neu la manager thi
       {
           //try
           //{
             
               var id = ConnectHostService.Prodiver().SaveUser(out error,Helper.ConvertObject.ConvertObjectToJsonString(_model), "Register new user", "50KWeb");
               if (error != null && error.Length > 0)
               {
                   return -1;
               }
               if (id > 0)
               {
                   return id;
               }

               return -1;
               /*code cu dung socket
               //command: Register service|user|message|type
               //Type equal zero number is normal user
               //Type equal one number is manager user
               StartSocket();
               var user = (users)_model;
              // user.password = 
               if (state != null && state == "OK")//Waiting for authurization from server
               {
                   socket.SendJson("RegisterNew", user.username, user+"|0");
                   int timeout = 0;
                   while (true)
                   {
                       if (socket.Data != null)
                       {
                           if (socket.Data.Contains("OK"))
                           {
                               socket.Stop();
                               timeout = 0;
                               return long.Parse(socket.Data.Split('|')[1].Split(' ')[1]);
                           }
                           else
                           {
                                socket.Stop();
                                error = socket.Data.Split('|')[1];
                                timeout = 0;
                               return -1; 
                           }
                          
                       }
                       timeout++;
                       Thread.Sleep(100);
                       if (timeout == 50)//qua 5 giay server khong phan hoi
                       {
                           error = ErrorCode.Error;
                           timeout = 0;
                           socket.Stop();
                           return -1;
                           //break;
                       }

                   }
                  
                  
               }
               return -1;*/
           //}
           //catch
           //{

           //    error = ErrorCode.Error;
           //    /*
           //    socket.Stop();*/ return -1;
           //}
       }

       /// <summary>
       /// Get by ID
       /// </summary>
       /// <param name="_id"></param>
       /// <returns></returns>
       public CoreData.users GetByID(long _id)
       {
           try
           {
               var data = ConnectHostService.Prodiver().GetUserByID(_id,"50KWeb",SessionManagement.GetSessionReturnToString("Username"));
               var modelobject = ConvertObject.ConvertToObject(new users());
               Helper.ConvertObject.ConvertEntityToModel(data,ref modelobject);
               return (users)modelobject;
              // return entity.GetById(_id, Table.users.ToString());
           }
           catch { return null; }
       }

       /// <summary>
       /// Get List
       /// </summary>
       /// <returns></returns>
       public IList<CoreData.users> GetList()
       {
           try
           {
               var result = new List<users>();
               var data = ConnectHostService.Prodiver().GetUserList("50KWeb", SessionManagement.GetSessionReturnToString("Username"));
                if (data != null && data.Count() != 0)
                {
                    foreach(var item in data)
                    {
                        var modelobject = ConvertObject.ConvertToObject(new users());
                        Helper.ConvertObject.ConvertEntityToModel(item, ref modelobject);
                        result.Add((users)modelobject);
                    }
                }
                return result;
           }
           catch { return null; }

       }

       
       



       /// <summary>
       /// Delete
       /// </summary>
       /// <param name="_model"></param>
       /// <returns></returns>
       public bool Delete(object _model)
       {
           try
           {
               return ConnectHostService.Prodiver().DeleteUser(((CoreData.users)_model).id);
             
           }
           catch { return false; }
       }


       #endregion



        #region Other Method

        public bool Login(string username, string password, out IList<vwusers> data)
        {
            try
            {
                var info = ConvertObject.ConvertJsonToListObject<vwusers>(ConnectHostService.Prodiver().GetViewUserByUserNameAndPassword(username, password, "50KWeb"));
                IList<vwusers> result = new List<vwusers>();

                foreach (var item in info)
                {
                    var modelobject = ConvertObject.ConvertToObject(new vwusers());
                    Helper.ConvertObject.ConvertEntityToModel(item, ref modelobject);
                    result.Add((vwusers)modelobject);
                }
                data = result;
                if (data == null || data.Count <= 0)
                {
                    return false;
                }
                SessionManagement.SetSesionUseId(info.First().id.ToString());
                SessionManagement.SetSesionUsername(info.First().username.ToString());
                SessionManagement.SetSesionValue("Email",info.First().email.ToString());
                SessionManagement.SetSesionObject("UserData", data);
                return true;
            }
            catch { data = null; return false; }
            /*StartSocket();
            if (state != null && state == "OK")//Waiting for authurization from server
            {
                socket.Send("Login", username, username + "@" + password);
                int timeout = 0;
                while (true)
                {
                    if (socket.Data != null)
                    {
                        if (socket.Data.Contains("SendUserData"))
                        {
                            user = Helper.ConvertObject.ConvertJsonToObject<vwusers>(socket.Data.Replace("SendUserData", ""));
                            return true;
                        }
                        else
                        {
                            error = ErrorCode.LoginFailed;
                            break;
                            //khong thanh cong
                        }
                    }
                    timeout++;
                    Thread.Sleep(100);
                    if (timeout == 50)//qua 5 giay server khong phan hoi
                    {
                        error = ErrorCode.LoginFailed;
                        break;
                    }

                }
                timeout = 0;
            }
            user = null;
            return false;*/
        }

        public void Logout()
        {
            SessionManagement.SetSesionUseId(null);
            SessionManagement.SetSesionUsername(null);
            SessionManagement.SetSesionValue(null, null);
            SessionManagement.SetSesionObject(null, null);
        }

        #endregion 
    
    }
         
}
